package info.niwota.start.app;

import info.niwota.start.Debug;
import info.niwota.start.Preferences;
import info.niwota.start.R;
import info.niwota.start.ResourceInfo;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;

public class ChoiceListActivity extends ListActivity implements OnClickListener {

	private class InitTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onCancelled() {
			setProgressBarIndeterminateVisibility(false);
		}

		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected Void doInBackground(Void... params) {
			loadApps();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			try {
				updateUi();
			} finally {
				setProgressBarIndeterminateVisibility(false);
			}
		}
	}

	private static final String TAG = "ChoiceListActivity";

	private ChoiceListAdapter adapter;

	private ArrayList<ResourceInfo> apps = new ArrayList<ResourceInfo>();

	private Button btnOk;
	private Button btnCancel;
	
	protected String key;

	private int getCount() {
		return adapter.getCount();
	}

	public void loadApps() {
		if (Debug.DEBUG) {
			Log.d(TAG, "loadApps key: " + key);
		}
		apps.clear();
		AppLoader.loadApplicationByKey(this, apps, key);
	}

	private int getSelectedCount() {
		SparseBooleanArray ps = getListView().getCheckedItemPositions();
		int size = adapter.getCount();
		int cnt = 0;
		for (int i = 0; i < size; i++) {
			if (ps.get(i)) {
				cnt++;
			}
		}
		return cnt;
	}

	private ArrayList<ResourceInfo> getSelectedApps() {
		SparseBooleanArray ps = getListView().getCheckedItemPositions();
		ArrayList<ResourceInfo> ck = new ArrayList<ResourceInfo>();
		int size = adapter.getCount();
		for (int i = 0; i < size; i++) {
			if (ps.get(i)) {
				ck.add(adapter.getItem(i));
			}
		}
		return ck;
	}

//	private boolean hasSelected() {
//		SparseBooleanArray ps = getListView().getCheckedItemPositions();
//		int size = adapter.getCount();
//		for (int i = 0; i < size; i++) {
//			if (ps.get(i)) {
//				return true;
//			}
//		}
//		return false;
//	}

	private void updateUi() {
		if (Debug.DEBUG) {
			Log.d(TAG, "updateUi");
		}
		// set to reload
		getListView().setAdapter(adapter);
		//
		String[] el = getApps();
		ListView v = getListView();
		v.clearChoices();
		int pos = 0;
		for (ResourceInfo a : apps) {
			boolean ck = false;
			if (el != null) {
				for (int i = 0; i < el.length; i++) {
					String s = a.getIntent().getComponent().toString();
					if (el[i].equals(s)) {
						ck = true;
						break;
					}
				}
			}
			v.setItemChecked(pos++, ck);
		}
		refreshUi(v, true);
	}

	private String[] getApps() {
		if (Debug.DEBUG) {
			Log.d(TAG, "getApps key: " + key);
		}
		String s = Preferences.getApps(this, key);
		if (TextUtils.isEmpty(s)) {
			return null;
		}
		return AppLoader.toStringArray(s);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate: " + savedInstanceState);
		}
		//
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.app_choice_list);
		//
		adapter = new ChoiceListAdapter(this, apps);

		setProgressBarIndeterminate(true);
		//
		final ListView lv = getListView();
		lv.setAdapter(adapter);
		lv.setItemsCanFocus(true);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		//
		setTitle("");
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon25);
		//
		View buttons = findViewById(R.id.buttons);
		buttons.setVisibility(View.VISIBLE);
		btnOk = (Button) findViewById(R.id.button_ok);
		btnCancel = (Button) findViewById(R.id.button_cancel);
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);

		apps.clear();
		
//		if (savedInstanceState != null) {
//			restore();
//			updateUi();
//		}
		
		init();
		new InitTask().execute();
	}

//	@SuppressWarnings("unchecked")
//	private void restore() {
//		Object[] obj = (Object[]) getLastNonConfigurationInstance();
//		ArrayList<ApplicationInfo> el = (ArrayList<ApplicationInfo>) obj[0];
//		if (el != null) {
//			apps.clear();
//			apps.addAll(el);
//		}
//	}

	private void init() {
		try {
			Uri uri = getIntent().getData();
			key = uri.getFragment();
			
			if (Debug.DEBUG) {
				Log.d(TAG, " init key: " + key + " uri: " + uri);
			}
			//
			apps.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void doCancel() {
		setResult(RESULT_CANCELED);
		finish();
	}

	private void doFinish() {
		Intent data = new Intent();
		ArrayList<ResourceInfo> list = getSelectedApps();
		if (list.size() > 0) {
			// data.putExtra("extra.app.list", list);
			String apps = AppLoader.toString(list);
			if (!TextUtils.isEmpty(apps)) {
				Preferences.putApps(this, key, apps);
			}
			
		} else {
			Preferences.putApps(this, key, null);
		}
		
		setResult(RESULT_OK, data);
		
		finish();
		//
		if (Debug.DEBUG) {
			Log.d(TAG, "doFinish " + data);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		int sc = getSelectedCount();
		updateTitle(sc);
		showOrHideActions(sc > 0);
	}

	protected void showActions() {
		btnOk.setEnabled(true);
	}

	protected void hideActions() {
		btnOk.setEnabled(false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	}

	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.button_ok:
			doFinish();
			break;
		case R.id.button_cancel:
			doCancel();
			break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return false;
	}

	private void refreshUi(ListView v, boolean show) {
		int sc = getSelectedCount();
		updateTitle(sc);
		showOrHideActions(show && sc > 0);
		v.requestLayout();
	}

	protected void showOrHideActions(boolean b) {
		if (b) {
			showActions();
		} else {
			hideActions();
		}
	}

	protected void updateTitle(int sc) {
		int tc = getCount();
		String t = "(" + sc + "/" + tc + ")";
		setTitle(t);
	}

}
